package com.example.blogapi.service;

import com.example.blogapi.dao.UserDao;
import com.example.blogapi.model.User;

import java.sql.SQLException;
import java.util.List;

public class UserService {
    private final UserDao userDao;

    public UserService() {
        this.userDao = new UserDao();
    }

    public List<User> getAllUsers() throws SQLException {
        return userDao.findAll();
    }

    public User getUserById(Long id) throws SQLException {
        return userDao.findById(id);
    }

    public User createUser(User user) throws SQLException {
        // 检查用户名是否已存在
        User existingUser = userDao.findByUsername(user.getUsername());
        if (existingUser != null) {
            throw new IllegalArgumentException("Username already exists");
        }
        
        return userDao.create(user);
    }

    public User updateUser(Long id, User user) throws SQLException {
        User existingUser = userDao.findById(id);
        if (existingUser == null) {
            throw new IllegalArgumentException("User not found");
        }

        // 如果用户名已更改，检查新用户名是否已存在
        if (!existingUser.getUsername().equals(user.getUsername())) {
            User userWithSameUsername = userDao.findByUsername(user.getUsername());
            if (userWithSameUsername != null) {
                throw new IllegalArgumentException("Username already exists");
            }
        }

        user.setId(id);
        user.setCreatedAt(existingUser.getCreatedAt());
        return userDao.update(user);
    }

    public boolean deleteUser(Long id) throws SQLException {
        User existingUser = userDao.findById(id);
        if (existingUser == null) {
            throw new IllegalArgumentException("User not found");
        }
        
        return userDao.delete(id);
    }
}